//
//  TextFieldSwiftUIView.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/27.
//

import SwiftUI
/*
  输入下啦提示框
 */

struct TextFieldSwiftUIView: View {
    // 输入框的文本绑定
    @State private var searchText = ""
    // 模拟数据源
    private let data = ["apple", "banana", "cherry", "date", "grape", "kiwi"]
    // 用来存储匹配的数据
    @State private var filteredData: [String] = []
    
    @State private var isChose = false
       
    var body: some View {
        VStack {
            TextField("Search", text: $searchText)
                .padding()
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .onChange(of: searchText) { newValue in
                       
                    if isChose{
                        isChose = false
                    }else{
                        // 每当输入变化时，过滤数据
                        filterData(query: newValue)
                    }
                       
                      
                }
               
            if !filteredData.isEmpty {
                List(filteredData, id: \.self) { item in
                    Text(item)
                        .onTapGesture {
                            // 点击某一项，更新输入框的内容
                            searchText = item
                            filteredData = [] // 选择后隐藏列表
                            isChose = true
                        }
                }
                .frame(height: 150)
                .cornerRadius(10)
                .shadow(radius: 5)
            }
        }
        .padding()
    }
       
    private func filterData(query: String) {
        // 如果搜索文本为空，清空过滤列表
        if query.isEmpty {
            filteredData = []
        } else {
            // 根据搜索文本过滤数据源
            filteredData = data
                .filter { $0.lowercased().contains(query.lowercased()) }
        }
    }
}

#Preview {
    TextFieldSwiftUIView()
}
